"use client"
import React, { useCallback } from 'react';
import {
  ReactFlow,
  useNodesState,
  useEdgesState,
  addEdge,
} from '@xyflow/react';
import {
  cloneDeep,
  groupBy,
  isEqual,
  uniqBy,
} from 'lodash-es'
import dagre from '@dagrejs/dagre'
import '@xyflow/react/dist/style.css';
import { Hint } from '@/components/hint';
import { Button } from '@/components/ui/button';
import { BrainCircuit, Notebook } from 'lucide-react';
import { run } from "@/services/run";
import { useLayout } from '@/features/workflow/hooks/use-workflow';


const initialNodes = [
  { id: '1', position: { x: 0, y: 0 }, height: 30, width: 100, data: { label: '1' } },
  { id: '2', position: { x: 0, y: 100 }, height: 30, width: 100, data: { label: '2' } },
  { id: '3', position: { x: 0, y: 100 }, height: 30, width: 100, data: { label: '3' } },
  { id: '4', position: { x: 0, y: 100 }, height: 30, width: 100, data: { label: '4' } },
  { id: '5', position: { x: 0, y: 100 }, height: 30, width: 100, data: { label: '5' } },
  { id: '6', position: { x: 0, y: 100 }, height: 30, width: 100, data: { label: '6' } },
];
const initialEdges = [
  { id: 'e1-2', source: '1', target: '2' },
  { id: 'e3-2', source: '3', target: '2' },
  { id: 'e2-5', source: '2', target: '5' },
  { id: 'e4-5', source: '4', target: '5' }
];

export default function App() {
  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
  const { organize } = useLayout()

  const onConnect = useCallback(
    (params) => setEdges((eds) => addEdge(params, eds)),
    [setEdges],
  );

  return (
    <div className="h-full flex flex-col">
      <nav className="w-full flex items-center p-4 h-[68px] gap-x-8 border-b lg:pl-[34px]">
        <Hint label="select" side="top" align="end" sideOffset={-10}>
          <Button variant="ghost"
            size="icon"
            onClick={run}
            className=""
          >
            <BrainCircuit />
          </Button>
        </Hint>
        <Hint label="select" side="top" align="end" sideOffset={-10}>
          <Button variant="ghost"
            size="icon"
            onClick={() => { organize(nodes, edges, setNodes) }}
            className=""
          >
            <Notebook />
          </Button>
        </Hint>
      </nav>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
      />
    </div>
  );
}